package com.haibo.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.haibo.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @Author : 刘海波
 * @Date: 2025-07-11 18:34
 * @Description:
 */
@Slf4j
public class EncryptUtil {

    /**
     *
     * URL解码
     * @param urlEncoded url编码后的数据
     * @return
     */
    public static String decodeUrl(String urlEncoded) {
        try {
            String decodedUrl = URLDecoder.decode(urlEncoded, StandardCharsets.UTF_8.name());
            return decodedUrl;
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    public static String sourceEncrypt(String plainText, String key) {
        try {
            // 创建 AES 密钥规范，密钥需为 16、24 或 32 字节
            SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");

            // 获取 AES ECB PKCS5 填充模式的 Cipher 实例
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");

            // 以加密模式初始化 Cipher
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);

            // 将明文转换为字节数组
            byte[] plainTextBytes = plainText.getBytes(StandardCharsets.UTF_8);

            // 执行加密操作
            byte[] encryptedBytes = cipher.doFinal(plainTextBytes);

            // 对加密后的字节数组进行 Base64 编码
            String base64Encoded = Base64.getEncoder().encodeToString(encryptedBytes);

            // 对 Base64 编码后的字符串进行 URL 编码
            return java.net.URLEncoder.encode(base64Encoded, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new BusinessException("解密异常");
        }
    }

    public static String encrypt(String strToEncrypt, String secret) throws Exception{
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(secret.getBytes(), "AES"));
        return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8)));
    }

    public static JSONObject decryData2JSONObject(String sourceData, String key){
        try {
            // 1. URL解码
            String urlDecoded = sourceData;

            // 2. Base64解码（假设密文经过Base64编码）
            byte[] encryptedBytes = Base64.getDecoder().decode(urlDecoded);


            byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES");

            // 4. 初始化解密器（使用ECB模式和PKCS5Padding填充）
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);

            // 5. 执行解密
            byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
            String decryptedText = new String(decryptedBytes, StandardCharsets.UTF_8);
            return  JSON.parseObject(decryptedText);
        } catch (Exception e) {
            // 根据实际情况处理异常（如密钥长度不匹配、解码失败等）
            e.printStackTrace();
            log.info("解密失败，失败原因：{}",e.getMessage());
        }
        return null;
    }

    /**
     * 解析url，返回字符串
     * @param queryParam  加密参数：
     *                    即链接https://xiaoshan.huihaohealth.com/api/v1/redirect?mRjiw1C4dD7Q1hA5n9W%2BlbsikpKzmvcqy49Fq5xYMgJPSNtM1J6e1nDdiPfiSBOlv8dgKO0bV3BvhfnsvuMvfg%3D%3D，?后面的参数
     * @param keySecret     秘钥
     * @return
     */
    public static String decryData2String(String queryParam, String keySecret) {
        try {
            String decodedParam = URLDecoder.decode(queryParam, StandardCharsets.UTF_8.name());

            // Base64解码（假设密文经过Base64编码）
            byte[] encryptedBytes = Base64.getDecoder().decode(decodedParam);

            // 秘钥
            byte[] keyBytes = keySecret.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES");

            // 初始化解密器（使用ECB模式和PKCS5Padding填充）
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);

            // 执行解密
            byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
            String decryptedText = new String(decryptedBytes, StandardCharsets.UTF_8);

            return decryptedText;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("[解密失败]，原因：" + e.getMessage());
        }

    }
}
